<?php

/**
 * RaiseFormErrorLabel UIControl class
 * displays error for a field.
 *
 * @author Sam-Mauris Yong <hellclanner at live dot com>
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @abstract
 * @package Raise.Core.UI.Form
 * @since 1.2
 */
class RaiseFormErrorLabel extends RaiseUIControl {

    /**
     * The field to load error
     * @var string
     */
    protected $field;

    /**
     * The CSS class names
     * @var string
     */
    protected $cssClass;

    /**
     * Create a new RaiseFormErrorLabel
     * @param string $field
     */
    public function __construct($field){
        $this->field($field);
    }
    
    /**
     * Get or set the field name that has this error
     * @param string $f (optional) Set the field name that has this error
     * @return string
     */
    public function field($f = null){
        if(func_num_args() == 1){
            $this->field = $f;
        }
        return $this->field;
    }

    /**
     * Get or set the CSS class names of this form field.
     * @param string $c (optional) If passed in, the new value will be set.
     * @return string
     */
    public function cssClass($c = null){
        if(func_num_args() == 1){
            $this->cssClass = $c;
        }
        return $this->cssClass;
    }

    /**
     * Creates a new RaiseFormErrorLabel and output it
     * @param RaisePage $page The current page
     * @param string $field The field
     * @param string $css (optional) The css class
     */
    public static function create($page, $field, $css = null){
        $a = new RaiseFormErrorLabel($field);
        $a->page($page);
        if($css){
            $a->cssClass($css);
        }
        return $a->output();
    }

    public function output(){
        $list = $this->page()->application()->session()->get(RaisePostbackFeedback::SESSION_KEY);
        $ex = false;
        if($list instanceof RaiseTypedCollection && $list->type() == 'RaiseFieldFeedback'){
            $feedback = $list->get($this->field);
            if($feedback){
                $ex = $feedback->exceptions();
            }
        }
        if($ex){
            $html = '';
            foreach($ex as $e){
                $message = $e->getMessage();
                $tag = RaiseHtml::tag('div', $message, array('id' => $this->clientId()));
                if($this->cssClass()){
                    $tag->attributes()->add('class', $this->cssClass());
                }
                $html .= $tag->html();
            }
            return $html;
        }else{
            return '';
        }
    }

}
